package top.scauwlt.config;

import lombok.extern.slf4j.Slf4j;
import top.scauwlt.extension.ExtensionLoader;
import top.scauwlt.registry.RegistryClear;
import top.scauwlt.registry.zk.util.CuratorUtils;
import top.scauwlt.utils.threadpool.ThreadPoolFactoryUtil;

import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.UnknownHostException;

/**
 * @Author wmm
 * @Date 2022/7/25 16:18
 */
@Slf4j
public class CustomShutDownHook {
    private static final CustomShutDownHook CUSTOM_SHUT_DOWN_HOOK = new CustomShutDownHook();
    private final RegistryClear registryClear;

    public CustomShutDownHook() {
        registryClear = ExtensionLoader.getExtensionLoader(RegistryClear.class).getExtension(RpcConfig.getInstance().getRegistryType());
    }

    public static CustomShutDownHook getCustomShutDownHook() {
        return CUSTOM_SHUT_DOWN_HOOK;
    }

    public void clearAll() {
        log.info("clear all service form " + RpcConfig.getInstance().getRegistryType());
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            try {
                InetSocketAddress inetSocketAddress = new InetSocketAddress(InetAddress.getLocalHost().getHostAddress(), RpcConfig.getInstance().getNettyPort());
                // CuratorUtils.clearRegistry(CuratorUtils.getClient(), inetSocketAddress);
                registryClear.clearRegistry(inetSocketAddress);
            } catch (UnknownHostException e) {
            }
            ThreadPoolFactoryUtil.shutDownAllThreadPool();
        }));
    }
}
